/* eslint-disable */
<style lang="less">
 @import './layout.less';
</style>

<template>
  <a-layout-header class="header">
    <v-container>
      <div class="header-logo">
        <img src="~/assets/images/logo.png" alt="智源社区">
      </div>

      <nav class="header-nav">
        <a-menu
          mode="horizontal"
          :default-selected-keys="[activedNav]"
        >
          <a-menu-item
            v-for="nav in navlist"
            :key="nav.path"
            @click="onClickMenuItem(nav)"
          >
            <nuxt-link :to="nav.path">
              {{ nav.name }}
            </nuxt-link>
          </a-menu-item>
        </a-menu>
      </nav>

      <div class="header-search">
        <a-popover
          v-model="searchInputActived"
          trigger="none"
          placement="bottom"
          overlay-class-name="header-search-popover"
        >
          <div
            class="header-search-wrapper"
            :class="{ 'header-search-wrapper__actived': searchInputActived }"
            @click="stopBubbleEvent"
          >
            <a-input-search
              allow-clear
              placeholder="请输入..."
              @blur="onBlur"
              @focus="onFocus"
              @change="onChange"
              @search="onSearch"
            >
              <a-button
                slot="enterButton"
                type="dark"
              >
                <v-icon type="search" />
              </a-button>
            </a-input-search>
          </div>

          <template slot="content">
            <div
              class="header-search-content"
              @click="stopBubbleEvent"
            >
              <!-- 搜索历史&搜索热词 -->
              <div
                v-show="visible.history"
                class="header-search-history"
              >
                <div class="header-search-section">
                  <div class="header-search-section-head">
                    <h4 class="header-search-section-title">
                      搜索历史
                    </h4>

                    <div class="header-search-section-extra">
                      <div
                        v-show="hasTags && !tagClosable"
                        class="header-search-text"
                      >
                        <v-icon
                          type="trash"
                          @click="onToggleTagEdit"
                        />
                      </div>

                      <div
                        v-show="tagClosable"
                        class="header-search-text"
                      >
                        <a
                          class="header-search-action"
                          @click="onClearHistory"
                        >全部删除</a>
                        <a
                          class="header-search-action"
                          @click="onToggleTagEdit"
                        >完成</a>
                      </div>
                    </div>
                  </div>

                  <div class="header-search-section-body">
                    <div
                      v-show="!hasTags"
                      class="header-search-section-empty"
                    >
                      暂无搜索历史
                    </div>

                    <v-tags
                      v-show="hasTags"
                      :data-source="tags"
                      :closable="tagClosable"
                      @close="onDeleteTagItem"
                    />
                  </div>
                </div>

                <div
                  v-if="hasHotKeys"
                  class="header-search-section"
                >
                  <div class="header-search-section-head">
                    <h4 class="header-search-section-title">
                      搜索热词
                    </h4>
                  </div>

                  <div class="header-search-section-body">
                    <div class="hot-keys">
                      <div
                        v-for="(key, idx) in hotKeys"
                        :key="key"
                        :class="['hot-keys-item', { 'font-bold': idx < 4 }]"
                      >
                        <nuxt-link to="/">
                          <span
                            :class="['hot-keys-num', { 'text-danger': idx < 4 }]"
                          >{{ idx + 1 }}</span>{{ key }}<v-icon v-if="idx === 0" image type="hot" />
                        </nuxt-link>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 搜索关键词匹配 -->
              <div
                v-show="visible.search"
                class="header-search-list"
              >
                <a-list item-layout="horizontal" :data-source="data">
                  <a-list-item
                    slot="renderItem"
                    slot-scope="item"
                    @click="onClickSearchItem(item.link)"
                  >
                    <a-list-item-meta>
                      <span
                        slot="title"
                        v-html="matchKeyword(item.title, keyword)"
                      />

                      <a-avatar
                        v-if="item.avatar"
                        slot="avatar"
                        :src="item.avatar"
                      />
                    </a-list-item-meta>
                  </a-list-item>
                </a-list>
              </div>
            </div>
          </template>
        </a-popover>
      </div>

      <div class="header-publish">
        <nuxt-link to="/">
          <!-- TODO: ICON 透明 -->
          <v-icon image type="edit" />
          <span>发布</span>
        </nuxt-link>
      </div>

      <div class="header-notify">
        <nuxt-link to="/">
          <v-icon image type="chat" />
          <i class="dot" />
        </nuxt-link>
      </div>

      <div class="header-user">
        <a-popover
          trigger="click"
          placement="bottom"
          overlay-class-name="popover"
        >
          <a href="javascript:;">
            <img src="~/assets/images/avatar.png" alt="" class="header-user-avatar">
            <span class="header-user-honor">200</span>
            <v-icon image type="honor" />
          </a>

          <template slot="content">
            <v-todos
              :data-source="[
                { id: '/my', name: '我的主页', icon: 'person' },
                { id: '/settings', name: '设置', icon: 'setting' },
                { id: '/?3', name: '退出', icon: 'logout' },
              ]"
              @click="onClickPopMenu"
            />
          </template>
        </a-popover>
      </div>
    </v-container>
  </a-layout-header>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import Container from './container'
import { SEARCH_HISTORY_KEY } from '~/constants'
import Todos from '~/components/todos'
import Icon from '~/components/icon'
import Tags from '~/components/tags'
import avatar from '~/assets/images/default.png'

const data = [
  {
    title: '搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题 1',
    link: '/',
  },
  {
    title: '搜索标题 2',
    link: '/',
  },
  {
    title: '搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题搜索标题 3',
    link: '/',
    avatar,
  },
  {
    title: '搜索标题 4',
    link: '/',
    avatar,
  },
  {
    title: '搜索标题 2',
    link: '/',
    avatar,
  },
  {
    title: '搜索标题 3',
    link: '/',
  },
  {
    title: '搜索标题 4',
    link: '/',
    avatar,
  },
  {
    title: '搜索标题 4',
    link: '/',
    avatar,
  },
  {
    title: '搜索标题 2',
    link: '/',
    avatar,
  },
  {
    title: '搜索标题 3',
    link: '/',
    avatar,
  },
  {
    title: '搜索标题 4',
    link: '/',
    avatar,
  },
]

const hotKeys = [
  '图神经网络1',
  '自然语言处理2',
  '图神经网络3',
  '自然语言处理4',
  '图神经网络5',
  '自然语言处理6',
  '图神经网络7',
  '自然语言处理8',
  '图神经网络9',
  '自然语言处理10',
]

function formatHistory (history) {
  if (Array.isArray(history)) {
    return history
  }

  if (!history || typeof history !== 'string') {
    return []
  }

  return formatHistory(JSON.parse(history))
}

export default {
  components: {
    'v-container': Container,
    'v-todos': Todos,
    'v-icon': Icon,
    'v-tags': Tags,
  },

  data () {
    return {
      data,
      hotKeys,
      keyword: '',
      tagClosable: false,
      searchInputActived: false,
      visible: {
        search: false,
        history: false,
      },
    }
  },

  computed: {
    ...mapState({
      navlist: ({ config = {} }) => {
        if (!Array.isArray(config.navlist)) {
          return []
        }

        return config.navlist
      },

      tags: ({ storage = {}, $storage }) => {
        const history = storage[SEARCH_HISTORY_KEY]

        return formatHistory(history)
      },

      // 选中的导航
      activedNav () {
        return this.$route.path
      },

      // 是否有搜索历史
      hasTags () {
        return Array.isArray(this.tags) && this.tags.length
      },

      // 是否有搜索热词
      hasHotKeys () {
        return Array.isArray(this.hotKeys) && this.hotKeys.length
      },
    }),
  },

  created () {
    const history = this.getHistory()

    this.updateHistory(history)
  },

  mounted () {
    document.addEventListener('click', (ev) => {
      this.searchInputActived = false
    }, false)
  },

  methods: {
    ...mapMutations({
      changeFooter: 'config/changeFooter',
    }),

    // 获取搜索历史
    getHistory () {
      const history = this.$storage.getUniversal(SEARCH_HISTORY_KEY)

      return formatHistory(history)
    },

    // 更新搜索历史
    setHistory (value) {
      const history = this.getHistory()
      const nextHistory = history.filter(h => h !== value)

      this.updateHistory([value].concat(nextHistory))
    },

    // 更新搜索历史
    updateHistory (values) {
      this.$storage.setUniversal(SEARCH_HISTORY_KEY, JSON.stringify(values))
    },

    // 删除搜索历史
    removeHistory (value) {
      const history = this.getHistory()
      const nextHistory = history.filter(h => h !== value)

      this.updateHistory(nextHistory)
    },

    toggleSearchModal (keyword, data) {
      if (typeof keyword !== 'string') {
        const visible = !!keyword

        this.visible.search = visible
        this.visible.history = visible

        return
      }

      // 输入框无内容时
      if (!keyword.trim()) {
        this.visible.search = false
        this.visible.history = true

        return
      }

      // 输入框有内容时
      this.visible.search = Boolean(Array.isArray(data) && data.length)
      this.visible.history = false
    },

    onBlur () {
      // this.toggleSearchModal(false)
    },

    onFocus (ev) {
      this.searchInputActived = true

      this.toggleSearchModal(ev.target.value, this.data)
    },

    onChange (ev) {
      const value = ev.target.value.trim()

      this.keyword = value
      this.toggleSearchModal(value, this.data)
    },

    // 搜索
    onSearch (value) {
      const keyword = value.trim()

      if (keyword) {
        this.keyword = keyword
        // 搜索关键词存入搜索历史
        this.onAppendTagItem(keyword)
      }
    },

    onClickSearchItem (link) {
      this.$router.history.push(link)
    },

    onClickMenuItem (data) {
      this.changeFooter(data.useFooter)
    },

    onToggleTagEdit (ev) {
      this.tagClosable = !this.tagClosable
    },

    onDeleteTagItem (tag) {
      this.removeHistory(tag)
    },

    onAppendTagItem (tag) {
      this.setHistory(tag)
    },

    onClickPopMenu (data) {
      this.$router.push(data.id)
    },

    onClearHistory () {
      this.$storage.removeUniversal(SEARCH_HISTORY_KEY)
    },

    // 阻止时间冒泡
    stopBubbleEvent (ev) {
      // ev.preventDefault()
      ev.stopPropagation()
    },

    matchKeyword (content, keyword) {
      if (typeof keyword !== 'string' || !keyword.trim()) {
        return content
      }

      const re = new RegExp(keyword, 'gi')

      return content.replace(re, function ($0) {
        return `<span class="text-keyword">${$0}</span>`
      })
    },
  },
}
</script>
